package by.grsu.bso.persistence.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.sql.DataSource;



public class ConnectionProvider {
	private static final String JNDI_DB_REF = "java:/comp/env/jdbc/shopDB";
	private static final String JNDI_DB_REF_NOT_FOUND = "'java:/comp/env/jdbc/shopDB' is not found in JNDI";

	private static DataSource ds;

	static {
		try {
			Context ct = new InitialContext();
			ConnectionProvider.ds = (DataSource) ct.lookup(ConnectionProvider.JNDI_DB_REF);

		} catch (NamingException e) {
			throw new ExceptionInInitializerError(
					ConnectionProvider.JNDI_DB_REF_NOT_FOUND);

		}
	}

	public static Connection getConnection() {
		Connection conn = null;
		if (ConnectionProvider.ds != null) {
			try {
				conn = ConnectionProvider.ds.getConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return conn;

	}
}
